import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_elder/models/code_value_entity.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/a_elder/page/elder_search_page.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/viewmodel/model/combo_data_model.dart';

import '../../model/decode_qrcode_model.dart';
import '../../model/customer_info_model.dart';
import '../../net/response/customer_family_info.dart';
import '../../util/utils.dart';

class AddLeaveViewModel extends BaseViewModel {
  final ElderInfo? info;

  AddLeaveViewModel(BuildContext context, {this.info}) : super(context) {
    this.older = info;
  }

  ElderInfo? older;

  var leaveTime = "";

  var leaveReasonId = "";
  var leaveReasonName = "";

  var relationshipId = "";
  var relationshipName = "";

  var planBackTime = "";

  var backTime = "";

  var accompanyType = "2";

  var accompanyName = "";

  var leaveRemark = "";

  var accompanyMobile = "";

  var accompanyId = "";

  ComboDataModel _dataModel = ComboDataModel();

  DecodeQrcodeModel scanModel = new DecodeQrcodeModel();

  var oldModel = CustomerInfoModel();

  var relationList = <CodeValue>[];
  var familyList = <CustomerFamilyInfo>[];

  var syncData = [
    SyncLeaveData(name: '同步离院',id: "0",remark: "同步离院登记，登记即为离院，状态直接变成已离院。"),
    SyncLeaveData(name: '仅发起请假，后续操作确认离院',id: "1",),
    SyncLeaveData(name: '自动离院（离院时间到达后）',id: "2",),
  ];

  String selectSync = "";

  Future<void> selectOlder() async {
    older = await Go().push(ElderSearchPage(
      needBack: true,
      isSelected: false,
    ));
    if(older==null){
      return;
    }
    onGetCustomer();
    notifyListeners();
  }

  Future<void> scanOld() async {
    var result = await Utils.scan();
    if(result.isNullOrEmpty()){
      return;
    }
    showLoadingDialog();
    try {
      var data = await scanModel.decoed(result);
      hideDialog();
      if (data.typeCode == 1) {
        var old = await oldModel.getOldData(data.id!);
        older = ElderInfo(
            name: old.elderHumanName,
            roomNo: old.elderHumanRoom,
            id: old.elderHumanId);
        onGetCustomer();
        notifyListeners();
      } else {
        showToast("请扫描长者码");
      }
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  Future<void> onGetCustomer() async {
    familyList.clear();
    showLoadingDialog();
    try {
      familyList = await oldModel.getCustomerFamilyInfo(older!.id!.toString());
      hideDialog();
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  void selectFamily(){
    if(familyList.isEmpty){
      showToast("无可选联系人");
      return;
    }
    DataPickerView(context, familyList,onSubmitListener: (p1,p2,p3){
      var data = familyList[p1];
      accompanyName = data.name;
      accompanyId = data.id.toString();
      accompanyMobile = data.mobile?.replaceAll("手机:", "")??"";
      relationshipId = data.relationshipId.toString();
      relationshipName = data.relationshipName??"";
      notifyListeners();
    }).show();
  }

  Future<void> addLeave() async {
    if (older == null) {
      showToast("请选择长者");
      return;
    }
    if (leaveTime.isEmpty) {
      showToast("请选择外出时间");
      return;
    }
    if (leaveReasonId.isEmpty) {
      showToast("请选择外出事由");
      return;
    }
    // if (relationshipId.isEmpty) {
    //   showToast("请选择与长者关系");
    //   return;
    // }
    //
    // if (accompanyName.isEmpty) {
    //   showToast("请输入陪同人姓名");
    //   return;
    // }
    // if (accompanyMobile.isEmpty) {
    //   showToast("请输入陪同人联系电话");
    //   return;
    // }

    if(selectSync.isNullOrEmpty()){
      showToast("请选择是否同步确认离院");
      return;
    }

    var remark = syncData.firstWhere((element) => element.id==selectSync).remark;

    if(!remark.isNullOrEmpty()){
      var apply = await showApplyDialog(remark??"");
      if(!apply){
        return;
      }
    }

    // if (planBackTime.isEmpty) {
    //   showToast("请选择预计销假时间");
    //   return;
    // }

    showLoadingDialog(msg: "提交中...");
    try {
      var map = await PostRequest.addLeave(
          customerElderId: older?.id.toString()??"",
          leaveTime: leaveTime,
          leaveReasonId: leaveReasonId,
          accompanyType: accompanyType,
          planBackTime: planBackTime,
          backTime: backTime,
          accompanyMobile: accompanyMobile,
          relationshipId: relationshipId,
          accompanyName: accompanyName,
          accompanyId: accompanyId,
          leaveRemark: leaveRemark,
      sync: selectSync);
      hideDialog();
      var bean = ResponseData.fromJson(map);
      if ("0" == bean.code) {
        showToast("提交成功");
        sendMessage(SendMessageEvent(MessageConfig.FINISH_LEAVE_SIGN));
        finish();
      } else {
        showToast(bean.msg??"");
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  var _formats = [yyyy, "-", mm, "-", dd, " ", HH, ":", nn, ":", ss];

  void selectLeaveTime() {
    DatePicker.showDateTimePicker(context, onConfirm: (date) {
      leaveTime = formatDate(date!, _formats, LocaleType.zh);
      notifyListeners();
    });
  }

  void selectPlanBackTime() {
    DatePicker.showDateTimePicker(context, onConfirm: (date) {
      planBackTime = formatDate(date!, _formats, LocaleType.zh);
      notifyListeners();
    });
  }

  void selectBackTime() {
    DatePicker.showDateTimePicker(context, onConfirm: (date) {
      backTime = formatDate(date!, _formats, LocaleType.zh);
      notifyListeners();
    });
  }

  @override
  void init() {
    super.init();
    addModels([_dataModel]);
  }

  Future<void> selectReason() async {
    showLoadingDialog();
    try {
      var data = await _dataModel.getComboData(ComboDataModel.leaveReason);
      hideDialog();
      DataPickerView(context, data, onSubmitListener: (p1, p2, p3) {
        var item = data[p1];
        leaveReasonId = item.id.toString();
        leaveReasonName = item.name ?? "";
        notifyListeners();
      }).show();
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  Future<void> getRelationShip() async {
    try {
      relationList = await _dataModel.getComboData(ComboDataModel.relationShip);
    } catch (e) {}
  }

  Future<void> selectRelation() async {
    showLoadingDialog();
    try {
      relationList = await _dataModel.getComboData(ComboDataModel.relationShip);
      hideDialog();
      DataPickerView(context, relationList, onSubmitListener: (p1, p2, p3) {
        var item = relationList[p1];
        relationshipId = item.id.toString();
        relationshipName = item.name ?? "";
        notifyListeners();
      }).show();
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    getRelationShip();
  }

  Future<bool> showApplyDialog(String remark) async {
    var apply = await showCupertinoDialog<bool>(context: context, builder: (context){
      return CupertinoAlertDialog(title: Text("提示"),
      content: CommonText(remark),
      actions: [
        TextButton(onPressed: (){
          Go().pop(result: false);
        }, child: CommonText("取消",textColor: Colors.grey)),
        TextButton(onPressed: (){
          Go().pop(result: true);
        }, child: CommonText("确定",textColor: Colors.blueAccent)),
      ],);
    });
    return apply??false;
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.NFC_READ_IC_CARD){
      var cardNumber = event.obj as String;
      getCustomerInfo(cardNumber);
    }
  }

  Future<void> getCustomerInfo(String cardNumber) async {
    showLoadingDialog();
    try{
      var old = await oldModel.getCardAccount(physicalCardNo: cardNumber);
      older = await oldModel.getElderInfo(old.data!.human!.id.toString());
      hideDialog();
      notifyListeners();
    }catch(e){
      hideDialog();
      showToast(e.toNetError());
    }
  }
}

class SyncLeaveData{
  String? name;
  String? id;
  String? remark;

  SyncLeaveData({this.name, this.id, this.remark});
}
